package com.cloud.open.util;

import com.cloud.open.constant.Constants;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class IPUtils {

    private static final Pattern IPV4_PATTERN = Pattern.compile(
                    "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");

    public static boolean isValid(String ip) {
        return IPV4_PATTERN.matcher(ip).matches();
    }

    public static Set<String> buildWhitelistIp(String whitelistIp) {
        return StringUtils.isEmpty(whitelistIp) ? Collections.EMPTY_SET
                : Arrays.stream(whitelistIp.split(Constants.SEPARATOR)).map(v -> v.trim()).filter(v -> v.length() > 0).collect(Collectors.toSet());
    }

}
